'use strict';

import './modal.scss';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import ModalBox from './ModalBox';

class Modal extends Component {

	//默认参数
	static defaultProps = {
		mid : "modalId", //默认box 的 ID
		//btn: <a>弹窗</a>,//
		modalStyle:{}, //modal的样式
		className:'animated bounceInDown',
		style : {width:400, height:260}, //框样式
		showBack : null, //显示时候的回调
		closeBack : null //关闭时候的回调
	}
	
	//构造函数
	constructor (props) {
		super(props);
		this.state = {
			show: props.visible
		}
		this.div = document.createElement('div');
		this.div.setAttribute('class','mt-div');
	}

	componentWillUnmount() {
	 	//document.getElementById(this.props.mid); 
	 	this.div.remove();
        ReactDOM.unmountComponentAtNode(this.div);
	}

	//渲染div
	renderDiv(){
		var _this = this;
		var dom = document.getElementById(this.props.mid);
		//首次渲染即可
		if(!dom){
 			document.body.appendChild(this.div);
			ReactDOM.render(<ModalBox show={this.state.show} showOrHide={this.showOrHide.bind(this)} {...this.props}/>,this.div); //
		}
	}

	//隐藏显示
	showOrHide(show,callback){
		var _this = this;
		this.renderDiv();
		this.setState({
			show: !show
		},function(){
			if(_this.state.show){
				_this.props.showBack()
			}else{
				_this.props.closeBack()
			}
			if(callback){
				callback();
			}
		})
	}

	//更新弹窗里面的数据
	componentDidUpdate(prevProps){
		ReactDOM.render(<ModalBox show={this.state.show} showOrHide={this.showOrHide.bind(this)} set={this.state.set} {...this.props}/>,this.div);
	}

	//点击事件
	handleClick(){
		const _this = this;
		this.showOrHide(this.state.show);
	}

	render(){
		var Component = this.props.btn.type;
		var {children, ...other} = this.props.btn.props;
		return <Component ref="btn" onClick={this.handleClick.bind(this)} {...other}>{children}</Component>
	}
}

//主页
export default Modal;